#include <math.h>
#include "..\soft\program\sh88f516.h"
#include "..\soft\program\hardware.h"
#include "..\soft\program\addeal.h"
#include "..\soft\program\incl.h"
#include "..\soft\program\extn_variable.h"

const fp32	AD_FILTER_FACTOR[FILTER_NUM] = {0.9, 0.7, 0.5, 0.3, 0.1};
int32	AD_BUFF[AD_BUFF_NUM];

void slope_init(void)
{
	if((SYS_EEPROM.CalMax - SYS_EEPROM.CalZero) > 0)
	 {
	  slope_ad = (SYS_EEPROM.CalMax - SYS_EEPROM.CalZero) / MAXINTC;
	  slopewt = MAXINTC / (SYS_EEPROM.SysWtMax / SYS_EEPROM.SysWtD);
	 }
	 else
	  {
	   slope_ad = slopewt = 0;
	  }
}

void ad_filter(void)
{
	uint8	i = 0;
	int32	min = 0;
	int32	max = 0;
	int32	ad_average = 0;

	min = max = AD_BUFF[0];
	for(i = 0; i < (AD_BUFF_NUM - 1); i++)
	 {
	  ad_average += AD_BUFF[i];
	  if(max < AD_BUFF[i])
	   max = AD_BUFF[i];
	  if(min > AD_BUFF[i])
	   min = AD_BUFF[i];
	 }
	ad_average = ad_average - max - min;
	ad_average = ad_average / (AD_BUFF_NUM - 2);
	AD_VALUE = 0.5 * ad_average + 0.5 * AD_VALUE;
}


void ad_buff_update(uint8 flag)
{
	uint8	i = 0;

	if(!flag)
     {
      for(i = 0; i < AD_BUFF_NUM; i++)
       AD_BUFF[i] = AD_VALUE_NEW;
      AD_BUFF_HEAD = 0;
  	 }
     else
      {
       AD_BUFF[AD_BUFF_HEAD] = AD_VALUE_NEW;
	   AD_BUFF_HEAD++;
	   if(AD_BUFF_HEAD == AD_BUFF_NUM)
	    AD_BUFF_HEAD = 0;
      }
}


void ad_update(void)
{
	uint8	i = 0;
	int32	ad_temp = 0;

	AD_VALUE_LAST = AD_VALUE;

	if(!AD_BUFF_FLAG)
	 {
	  ad_buff_update(AD_BUFF_FLAG);
	  AD_BUFF_FLAG = 1;
	  AD_VALUE = AD_VALUE_NEW;
	 }
	 else
	  {
	   if(labs(AD_VALUE -  AD_VALUE_NEW) > AD_PULSE_VALUE)
	    {
		 AD_PULSE_COUNT++;
		 if(AD_PULSE_COUNT > AD_PULSE_COUNT_MAX)
		  {
		   AD_PULSE_COUNT = 0;
	       ad_buff_update(0);
		   AD_BUFF_FLAG = 1;
	       AD_VALUE = AD_VALUE_NEW;
		  }
		}
		else
		 {
		  ad_buff_update(1);
		  AD_BUFF_FLAG = 1;
		  ad_filter();
		 }
	  }
}

void adread(void)
{
  if(StarADFlag)
   {
//    AD_VALUE_NEW = ADS1232_Result();
	AD_NEW_FLAG = 1;
   }
   else
    {
     if(!ADDATA)
      StarADFlag = 1;
    }
}
void ad_deal(void)
{
   if(AD_NEW_FLAG)
   {
    AD_NEW_FLAG = 0;
    AD_VALUE_NEW = ADS1232_Result();
	ad_update();
	stabletest();
	ad_180000_conv();
    AD_UPDATE_FLAG = 1;
   }

/*	if(!ADTIME)
	 {
	  ADTIME = AD10MS;
	  if(!ADDATA)
	   {
	    AD_VALUE_NEW = ADS1232_Result();
		ad_update();
		stabletest();
		ad_180000_conv();
		AD_UPDATE_FLAG = 1;
	   }
	 }
	 else
	  {
	   AD_UPDATE_FLAG = 0;
	   ADTIME--;
	  }	*/
}

void stabletest(void)
{
	   if(labs(AD_VALUE - AD_VALUE_LAST) < 10)
	    STABLE_FLAG = 1;
		else
		 STABLE_FLAG = 0;
}


void ad_180000_conv(void)
{
	if(slope_ad != 0)
	 GWEIGHT_AD = (AD_VALUE - WTZERO) / slope_ad;
	 else
	  GWEIGHT_AD = 0;
}





